import React from 'react';
import { Spin } from 'antd';
import { history } from 'react-router-dom';
import MultiTabMobx from '@/store/multiTab';

import {
  ElCard,
  ElEditTable,
  ElForm,
  ElRowContainer,
  ElSearchTable
} from '@/components/el';

import {
  getBasicItemForm,
  getOrderDetailColumns,
  getOrderReceiverDetailColumns
} from './config';

import { getReceiptDetail, findDetail, getReceiptDetailById } from '../service';

import '../style.less';

interface Props {
  history: history;
  match: any;
  store: any;
  refresh: any;
  cacheKey: any;
}

interface State {
  id: string | number;
  loading: boolean;
  docTypeData: Array<any>;
  orderSelectedRowKeys: Array<any>;
  bascicFormDate: any;
  datailData: Array<any>;
  receiptInfoData: Array<any>;
  docType2: any;
}

class WorkOrderView extends React.Component<Props, State> {
  constructor(props) {
    super(props);
    this.multiTabStore = MultiTabMobx;

    this.state = {
      id: this.props.match?.params?.id, //单据id
      loading: false, //页面级loading
      docTypeData: [], //订单类型下拉数据
      orderSelectedRowKeys: [], //订单明细表格选择行rowkey
      bascicFormDate: {}, //基本信息
      datailData: [], // 订单明细数据
      receiptInfoData: [], // 收款信息数据
      docType2: '' // 订单类型
    };
  }

  multiTabStore: any;
  tabsRef: any;
  basicFormRef: any; //基础信息表单ref
  orderDeatilRef: any; // 订单明细可编辑表格ref
  receiverInfoRef: any; // 订单收款明细ref

  async componentDidMount() {
    this.setState({
      loading: true,
      docType2: ''
    });

    // 查询详情接口
    findDetail({ salSoId: this.state.id }).then(async (res) => {
      if (res && res.success) {
        const { docCls, soScene, salSoDSaveVOList } = res.data;

        // 如果是C端订单，默认加载收款信息
        if (res.data?.docType2 === 'C') {
          this.receiverInfoRef.setLoading(true);
          getReceiptDetailById(this.state.id).then((resp) => {
            if (resp?.success) {
              this.setState({ receiptInfoData: resp?.data });
            }
            this.receiverInfoRef.setLoading(false);
          });
        }

        this.setState({
          bascicFormDate: res.data,
          datailData: salSoDSaveVOList,
          loading: false,
          docType2: res.data?.docType2
        });
      } else {
        this.setState({
          loading: false
        });
      }
    });
  }

  /** 返回 */
  onBack = () => {
    this.props.store.MultiTabMobx.closeCurrentToPath(
      '/order/workOrder/list',
      () => false
    );
  };

  /**
   * 订单明细行选择事件
   * @param selectedRowKeys
   * @param selectedRows
   */
  handleOrderInfoSelect = (selectedRowKeys, selectedRows) => {
    const { docType2 } = this.state;
    // 如果是B端订单，通过明细查询收款信息
    if (docType2 !== 'C') {
      this.setState({
        orderSelectedRowKeys: selectedRowKeys
      });
      this.receiverInfoRef.setLoading(true);
      const id = selectedRows[selectedRows?.length - 1]?.id;
      // 获取 订单收款明细信息
      getReceiptDetail(id).then((res) => {
        if (res.success) {
          this.setState({ receiptInfoData: res?.data });
        }
        this.receiverInfoRef.setLoading(false);
      });
    }
  };

  render() {
    const { loading, bascicFormDate, receiptInfoData, datailData } = this.state;

    console.log(receiptInfoData, '===========');

    return (
      <Spin spinning={loading}>
        <ElRowContainer onBack={this.onBack} position='top' blocks={[]} />
        <ElCard className='formAlignment' title='基本信息'>
          <ElForm
            data={bascicFormDate}
            onRef={(ref: any) => {
              this.basicFormRef = ref;
            }}
            formProps={getBasicItemForm()}
          />
        </ElCard>
        <div>
          <ElCard title='订单明细' className='omsSaleOrderManageOrderInfo'>
            <div>
              <ElEditTable
                tableId='oms_saleorder_viewWorkOrderDetail'
                bordered
                needToolBar={false}
                scroll={{ x: 'max-content' }}
                onRef={(ref) => (this.orderDeatilRef = ref)}
                dataSource={datailData}
                columns={getOrderDetailColumns()}
                rowSelectionConfig={{
                  type: 'radio',
                  fixed: false,
                  disabledRowIds: [],
                  onChange: ({ selectedRowKeys, selectedRows }) => {
                    this.handleOrderInfoSelect(selectedRowKeys, selectedRows);
                  }
                }}
              />
            </div>
          </ElCard>
          <ElCard title='订单收款明细' className='receiveStyle'>
            <ElSearchTable
              tableId='oms_saleorder_workOrderView'
              rowKey='id'
              bordered
              onRef={(ref) => (this.receiverInfoRef = ref)}
              rowSelectionConfig={null}
              scroll={{ x: 'min-content', y: 'calc(100vh - 310px)' }}
              mode={{
                // 精简模式,是否隐藏搜索表格的某一块元素
                proxy: false, // 筛选器
                search: false, // SearchForm
                action: true, // actionButtons
                pagination: true, // 分页
                descriptions: false // descriptions
              }}
              dataSource={receiptInfoData}
              columns={getOrderReceiverDetailColumns()}
            />
          </ElCard>
        </div>
      </Spin>
    );
  }
}

export default WorkOrderView;
